package com.example.java8;

import org.springframework.util.StopWatch;

import java.util.*;
import java.util.stream.Collectors;

public class StreamPerformanceTest {
    private static StreamPerformanceTest ourInstance = new StreamPerformanceTest();

    public static StreamPerformanceTest getInstance() {
        return ourInstance;
    }

    private StreamPerformanceTest() {
    }

    public static void main(String[] args) {
        List<Student> studentsList = new ArrayList<Student>();
        for (int i = 0; i < 100; i++) {
            Random random = new Random();
            Student s3 = new Student(i / 2 == 0 ? "2" : "1", random.nextInt());
            studentsList.add(s3);
        }


        Map<String, List<Student>> stuMap = new HashMap<String, List<Student>>();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("传统for循环");
        for (Student stu : studentsList) {
            if (stu.getHeight() > 160) { //如果身高大于160
                if (stuMap.get(stu.getSex()) == null) { //该性别还没分类
                    List<Student> list = new ArrayList<Student>(); //新建该性别学生的列表
                    list.add(stu);//将学生放进去列表
                    stuMap.put(stu.getSex(), list);//将列表放到map中
                } else { //该性别分类已存在
                    stuMap.get(stu.getSex()).add(stu);//该性别分类已存在，则直接放进去即可
                }
            }
        }
        stopWatch.stop();
        System.out.printf("传统for循环执行时长：%d 毫秒.%n",stopWatch.getLastTaskTimeMillis());

        //串行
        stopWatch.start("串行streamfor循环");
        Map<String, List<Student>> stuMap1 = studentsList.stream().filter((Student s) -> s.getHeight() > 160).collect(Collectors.groupingBy(Student::getSex));
        stopWatch.stop();
        System.out.printf("串行streamfor循环执行时长：%d 毫秒.%n",stopWatch.getLastTaskTimeMillis());
        //并行
        stopWatch.start("并行streamfor循环");
        Map<String, List<Student>> stuMap2 = studentsList.parallelStream().filter((Student s) -> s.getHeight() > 160).collect(Collectors.groupingBy(Student::getSex));
        stopWatch.stop();
        System.out.printf("并行streamfor循环执行时长：%d 毫秒.%n",stopWatch.getLastTaskTimeMillis());
        System.out.println(stopWatch.prettyPrint());
    }

}

class Student {
    public Student(String sex, int height) {
        this.sex = sex;
        this.height = height;
    }

    private String sex;

    private int height;


    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}
